Use case: User application erase in polling mode

Use case applicable in HAL2 only for FLASH.

Important

When using HAL_FLASH_EraseByAddr(), note that because the hardware flash controller erases entire fixed-size pages, if the start or end address falls within a page, the whole page(s) containing those addresses will be erased. The erased area can therefore be larger than the specified range.

Sequence diagram

User application erase in polling mode (HAL1)

@startuml
title: User application erase in polling mode (HAL1)

hide footbox
participant "User Application" as User
participant "FLASH" as FLASH

group #snow FLASH Unlock
   User -> FLASH : HAL_FLASH_Unlock()
end

group #snow FLASH Erase Operation
   User -> User : Fill EraseInitStruct\n- TypeErase = FLASH_TYPEERASE_<TARGET>\n- Banks = BankNumber\n- Sector/Page = First\n- NbSectors/NbPages = Count
   note right: <TARGET> can be SECTORS, MASSERASE, OBK_ALT
   User -> FLASH : HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError)
end

group FLASH Lock (recommended)
   User -> FLASH : HAL_FLASH_Lock()
end

@enduml

Code snippet

HAL1

HAL2

uint32_t FirstPage = GetPage(FLASH_USER_NS_START_ADDR);
uint32_t NbOfPages = GetPage(FLASH_USER_NS_END_ADDR) - FirstPage + 1;

/* Unlock the FLASH to enable the FLASH control register access */
HAL_FLASH_Unlock();

/* Fill EraseInit structure */
EraseInitStruct.TypeErase     = FLASH_TYPEERASE_PAGES;
EraseInitStruct.Banks         = BankNumber;
EraseInitStruct.Page          = FirstPage;
EraseInitStruct.NbPages       = NbOfPages;

HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError);

/* Lock the FLASH to disable the FLASH control register access */
HAL_FLASH_Lock();
hal_flash_handle_t flash_handle;
uint32_t page_number;
uint32_t number_of_pages;
uint32_t timeout;

/* FLASH initialization */
HAL_FLASH_Init(&flash_handle, HAL_FLASH);

/* Unlock the FLASH to enable the FLASH control register access */
HAL_FLASH_ITF_Unlock(HAL_FLASH);

#if defined (USE_HAL_FLASH_ERASE_PAGE) && (USE_HAL_FLASH_ERASE_PAGE == 1U)
HAL_FLASH_ErasePage(&flash_handle, HAL_FLASH_BANK_1, page_number, number_of_pages, timeout);
#endif /* USE_HAL_FLASH_ERASE_PAGE */

/* Lock the FLASH to disable the FLASH control register access */
HAL_FLASH_ITF_Lock(HAL_FLASH);

/* FLASH deinitialization */
HAL_FLASH_DeInit(&flash_handle);

Key changes

  1. HAL1 uses a filled erase init structure; HAL2 provides granular erase APIs (ByAddr/Page/Bank/Mass) with explicit parameters.

  2. HAL2 separates operational services (IO) from access control (ITF) using distinct unlock/lock APIs.

  3. Address-range erase in HAL2 remains page-aligned and may erase a wider area than requested.